﻿ 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Diagnostics;

namespace SysCommon.Log
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileReadWrite
    {
        /// <summary>
        /// 检查给定的文件路径，如果不存在就创建它
        /// </summary>
        /// <param name="FileName">文件路径和文件名</param>
        public static bool CheckFileNamePathDirectory(string FileName)
        {
            int i = FileName.LastIndexOf('\\');
            int j = FileName.LastIndexOf('/');

            if (i > -1 || j > -1)
            {
                string FilePath = "";
                if (i > -1)
                {
                    FilePath = FileName.Substring(0, i);
                }
                if (j > -1)
                {
                    FilePath = FileName.Substring(0, j);
                }
                if (!Directory.Exists(FilePath))
                {
                    Directory.CreateDirectory(FilePath);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 独立写入文件 不用判断是否存在这个相对路径
        /// </summary>
        /// <param name="sFilePath">文件相对路径（不能写绝对路径）</param>
        /// <param name="WriteLineString">要写入的信息</param>
        /// <param name="fFileMode">文件的打开方式</param>
        public static void IsolatedStorageFileStreamStreamWrite(string sFilePath, string WriteLineString, FileMode fFileMode)
        {
            // 创建当前用户的独立存储
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                int i = sFilePath.LastIndexOf('\\');
                if (i > -1)
                {
                    string FilePath = sFilePath.Substring(0, i);
                    store.CreateDirectory(FilePath);
                }
                // 创建一个独立存储文件
                using (Stream fs = new IsolatedStorageFileStream(sFilePath, fFileMode, store))
                {
                    StreamWriter writer = new StreamWriter(fs);
                    writer.WriteLine(WriteLineString);
                    writer.Flush();
                }
                //Debug.WriteLine("当前大小：" + store.CurrentSize.ToString() + Environment.NewLine);
                //Debug.WriteLine("范围：" + store.Scope.ToString() + Environment.NewLine);
                //string[] files = store.GetFileNames("*.*");
                //if (files.Length > 0)
                //{
                //    Debug.WriteLine("当前文件：" + Environment.NewLine);
                //    foreach (string file in files)
                //    {
                //        Debug.WriteLine(file + Environment.NewLine);
                //    }
                //}
            }
        }

        /// <summary>
        /// 写入文本文件 (没有这个路径本函数就会创建当前路径)
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <param name="WriteLineString">写入的文本</param>
        /// <param name="fFileMode">文件的打开方式</param>
        public static void FileStreamStreamWrite(string sPathFileName, string WriteLineString, FileMode fFileMode)
        {
            CheckFileNamePathDirectory(sPathFileName);
            using (FileStream fs = new FileStream(sPathFileName, fFileMode))
            {
                // 创建一个StreamWriter对象，使用UTF-8编码格式
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
                {
                    // 分别写入十进制数，字符串和字符类型的数据
                    writer.WriteLine(WriteLineString);
                }
            }
        }

        /// <summary>
        /// 共享写入文本文件 (没有这个路径本函数就会创建当前路径,在多线程中不会因独占而报错)
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <param name="WriteLineString">写入的文本</param>
        /// <param name="fFileMode">文件的打开方式</param>
        public static void FileStreamShareWrite(string sPathFileName, string WriteLineString, FileMode fFileMode)
        {
            CheckFileNamePathDirectory(sPathFileName);
            using (FileStream fs = new FileStream(sPathFileName, fFileMode, FileAccess.Write, FileShare.Write))
            {
                // 创建一个StreamWriter对象，使用UTF-8编码格式
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
                {
                    // 分别写入十进制数，字符串和字符类型的数据
                    writer.WriteLine(WriteLineString);
                }
            }
        }
        /// <summary>
        /// 读取文本文件
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <returns></returns>
        public static string FileStreamStreamRead(string sPathFileName)
        {
            if (!File.Exists(sPathFileName))
            {
                throw new Exception("指定的文件不存在");
            }
            using (FileStream fs = new FileStream(sPathFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                {
                    string textString = string.Empty;
                    while (!reader.EndOfStream)
                    {
                        string text = reader.ReadLine();
                        textString += text + Environment.NewLine;
                    }
                    return textString;
                }
            }
            return "";
        }

        /// <summary>
        /// 写入二进制文件 (没有这个路径本函数就会创建当前路径)
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <param name="WriteLineString">二进制字符串</param>
        /// <param name="fFileMode">文件的打开方式</param>
        public static void FileStreamBinaryWriter(string sPathFileName, string WriteLineString, FileMode fFileMode)
        {
            CheckFileNamePathDirectory(sPathFileName);
            using (FileStream fs = new FileStream(sPathFileName, fFileMode))
            {
                using (BinaryWriter writer = new BinaryWriter(fs))
                {
                    // 写入十进制数，字符串和字符
                    writer.Write(WriteLineString);
                }
            }

        }
        /// <summary>
        /// 写入二进制文件 (没有这个路径本函数就会创建当前路径)
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <param name="WriteLineString">二进制字符串</param>
        /// <param name="fFileMode">文件的打开方式</param>
        public static void FileStreamBinaryWriter(string sPathFileName, byte[] WriteLineByte, FileMode fFileMode)
        {
            CheckFileNamePathDirectory(sPathFileName);
            using (FileStream fs = new FileStream(sPathFileName, fFileMode))
            {
                using (BinaryWriter writer = new BinaryWriter(fs))
                {
                    // 写入十进制数，字符串和字符
                    writer.Write(WriteLineByte);
                }
            }
        }

        /// <summary>
        /// 读取二进制文件 
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <returns></returns>
        public static string FileStreamBinaryReader(string sPathFileName)
        {
            if (!File.Exists(sPathFileName))
            {
                throw new Exception("指定的文件不存在");
            }
            using (FileStream fs = new FileStream(sPathFileName, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    fs.Position = 0;
                    using (BinaryReader reader = new BinaryReader(fs))
                    {
                        // 选用合适的数据类型读取数据
                        //string message = reader.ReadDecimal().ToString() + Environment.NewLine;
                        return reader.ReadString();
                        //message += reader.ReadChar().ToString();
                    }
                }
            }
        }
        /// <summary>
        /// 读取二进制文件成二进制流
        /// </summary>
        /// <param name="sPathFileName">文件名称及路径（非网络路径）</param>
        /// <returns></returns>
        public static byte[] FileStreamReaderByte(string sPathFileName)
        {
            if (!File.Exists(sPathFileName))
            {
                throw new Exception("指定的文件不存在");
            }
            using (FileStream fs = new FileStream(sPathFileName, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    fs.Position = 0;
                    using (BinaryReader reader = new BinaryReader(fs))
                    {
                        // 选用合适的数据类型读取数据
                        return reader.ReadBytes((int)fs.Length);
                    }
                }
            }
        }
    }
}

